package com.allinpay.controller;

import com.allinpay.common.SybUtil;
import com.allinpay.pojo.PayLoad;
import com.allinpay.service.PayService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Map;
import java.util.TreeMap;

import static cn.hutool.core.util.IdUtil.getSnowflakeNextIdStr;

@RestController
@RequestMapping("Allinpay")
@RequiredArgsConstructor
@Slf4j
public class AllinpayController {


    private final PayService payService;


    /**
      * 下单支付接口
      * @param response 返回响应
      * @return {@link String}
      */
    @SneakyThrows
    @GetMapping("pay")
    public String pay(HttpServletResponse response) {
        String paymentUrl = (String) payService.h5Pay(new PayLoad()
                .setPayType(2)
                .setPayConfigKey("")
                .setReturnUrl("https://blog.csdn.net")
                .setOrderId(getSnowflakeNextIdStr())
                .setAmount(new BigDecimal(2))
                .setRemark("测试支付备注")
                .setTitle("测试H5支付")
        );
        String htmlResponse = "<!DOCTYPE html><html><head></head><body>"
                + "<script>window.location.href='" + paymentUrl + "'</script>"
                + "</body></html>";

        // 设置响应内容类型为HTML
        response.setContentType("text/html;charset=UTF-8");
        return htmlResponse;
    }

    /**
     * 查询订单
     * @param outTradeNo 下单的订单号
     * @return {@link String}
     ***/
    @SneakyThrows
    @GetMapping("query/{outTradeNo}")
    public Map<String, String> query(@PathVariable Long outTradeNo) {
        return handleResult(payService.query(new PayLoad().setOrderId(outTradeNo.toString())));
    }



    /**
     * 关闭订单
     * @param outTradeNo 下单的订单号，也就是你支付下单类Allinpay的reqsn
     * @return {@link String}
     *//**/
    @SneakyThrows
    @GetMapping("closeOrder/{outTradeNo}")
    public Map<String,String> closeOrder(@PathVariable Long outTradeNo) {
        return handleResult(payService.closeOrder(new PayLoad().setOrderId(outTradeNo.toString())));
    }


    /**
     * 退款接口，只能退今天的，全额退款，实时返回退款结果
     * @return {@link String}
     */
    @SneakyThrows
    @GetMapping("cancelDay/{outTradeNo}")
    public Map<String, String> cancelDay(@PathVariable Long outTradeNo) {
        return handleResult(payService.cancelDay(new PayLoad().setOrderId(outTradeNo.toString())));
    }

    // 可以和上面的接口进行整合处理

    /**
     * 退款接口,可以退部分
     * @return {@link String}
     */
    @SneakyThrows
    @GetMapping("refund/{outTradeNo}")
    public Map<String, String> refund(@PathVariable Long outTradeNo) {
        return handleResult(payService.refund(new PayLoad().setOrderId(outTradeNo.toString())));
    }


    /**
     * 其中通联返回验签代码
     * @param result
     * @return {@link Map}<{@link String},{@link String}>
     * @throws Exception
     */
    @SuppressWarnings({ "rawtypes", "all" })
    public static Map<String,String> handleResult(String result) throws Exception{
        Map map = SybUtil.json2Obj(result, Map.class);
        if(map == null){
            throw new Exception("返回数据错误");
        }
        if("SUCCESS".equals(map.get("retcode"))) {
            TreeMap tmap = new TreeMap();
            tmap.putAll(map);
            if(SybUtil.validSign(
                     tmap,
                    "xxxxx",
                    "RSA")
            ){
                return map;
            }else{
                throw new Exception("验证签名失败");
            }
            // 验签成功，返回数据
        }else{
            throw new Exception(map.get("retmsg").toString());
        }
    }

}
